package com.pwt.common;

import lombok.Data;
import org.springframework.data.domain.Page;

import java.io.Serializable;
import java.util.Collection;

/**
 * @author zhangyi
 */
@Data
public class Result implements Serializable {

    private int code;
    private String msg;

    private Integer count;
    private Object data;

    public Result(){}

    private Result(ResultCode resultCode) {
        this.code = resultCode.code();
        this.msg = resultCode.message();
    }


    private Result(int code,String msg,Integer count,Object data) {
        this.code = code;
        this.msg = msg;
        this.count = count;
        this.data = data;
    }

    public static Result success() {
        return new Result(ResultCode.SUCCESS);
    }

    public static Result success(Object data) {
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(data);
        if(data instanceof Collection) {
            result.setCount(((Collection) data).size());
        }
        return result;
    }
    public static Result success(Page data) {
        Result result = new Result(ResultCode.SUCCESS);
        result.setData(data.getContent());
        result.setCount((int) data.getTotalElements());
        return result;
    }

    public static Result failure(ResultCode resultCode) {
        return new Result(resultCode);
    }

    public static Result failure(ResultCode resultCode, Object data) {
        Result result = new Result(resultCode);
        result.setData(data);
        return result;
    }

    public static Result failure(CustomException exception) {
        String msg = exception.getMsg();
        int code = exception.getCode();
        Object data = exception.getData();
        return new Result(code,msg,null,data);
    }
}
